<template>
  <div>
    <ul class="el-upload-list el-upload-list--picture-card">
      <el-upload
        class="upload-demo"
        :action="XAction"
        multiple
        ref="uploada"
        :headers="XHeader"
        accept="image/jpg, image/jpeg, image/png"
        :show-file-list="false"
        :limit="XMaxImg"
        :on-change="compression ? handlePictureCardPreview : sss"
        :on-success="acv"
        :before-upload="beforeAvatarUpload"
        :auto-upload="compression ? false : true"
        list-type="picture-card"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <draggable v-model="images" @update="datadragEnd" class="dragArea">
        <li
          :tabindex="index"
          class="el-upload-list__item is-success animated"
          style="''"
          v-for="(element, index) in images"
        >
          <img :src="element.src" alt class="el-upload-list__item-thumbnail" />
          <a class="el-upload-list__item-name">
            <i class="el-icon-document"></i>
            @{{ element.name }}
          </a>
          <label class="el-upload-list__item-status-label">
            <i class="el-icon-upload-success el-icon-check"></i>
          </label>
          <i class="el-icon-close"></i>
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-delete">
              <i class="el-icon-delete" @click="remove(index)"></i>
            </span>
          </span>
        </li>
      </draggable>
    </ul>
    <p>
      {{
        "图片最多上传" +
        XMaxImg +
        "张，单图最大不能超过" +
        (maximum || 200) +
        "kb." +
        (XMaxImg > 1 ? "拖动图片进行排序更改." : "")
      }}
    </p>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import { compress } from "./lib";
import axios from "axios";
export default {
  components: {
    draggable,
  },
  props: {
    //网络地址
    XAction: String,
    //请求头
    XHeader: Object,
    //已存在图片
    XFileList: "",
    //最大图片数量
    XMaxImg: Number,
    //文字提示
    value: "",
    //上传最大kb不传默认200kb
    maximum: "",
    compression: false, //开启图片压缩
  },
  data() {
    return {
      show: false,
      images: [],
      Img: [],
      count: 0,
    };
  },
  destoryed() {
    this.images = [];
  },
  watch: {
    value: function (newVal, oldVal) {
      if (this.value) {
        this.CoverImgs(newVal);
      } else {
        this.images = [];
        this.Img = [];
        this.$refs.uploada.clearFiles();
      }
    },
  },
  mounted() {
    if (this.newValues) {
      this.CoverImgs(this.newValues);
    }
  },
  computed: {
    newValues: {
      get: function () {
        return this.value;
      },
      set: function (value) {
        this.$emit("input", value);
      },
    },
  },
  methods: {
    sss() {
      return;
    },
    handlePictureCardPreview(event, file, fileList) {
      const _that = this;
      const isLt10M = event.size / 1024 / 1024 < 5;
      if (!isLt10M) {
        this.$message({
          type: "warning",
          message: "上传图片大小不能超过 5M!",
          offset: 100,
        });
        return false;
      } else {
        compress(
          event.raw,
          (val) => {
            var formDate = new FormData();
            var imgs = window.URL.createObjectURL(val);
            var file = new File([val], "img.jpg", { type: "image/jpg" });
            formDate.append("file", file);
            var axiosInstance = axios.create();
            axiosInstance({
              method: "post",
              url: this.XAction,
              headers: { ApiAuth: this.XHeader.ApiAuth },
              data: formDate,
            }).then((res) => {
              if (res.data.code === 1) {
                this.images.push({
                  type: "image",
                  src: res.data.data.fileUrl,
                });
                if (this.XMaxImg == 1) {
                  this.newValues = JSON.parse(
                    JSON.stringify(this.images)
                  )[0].src;
                } else {
                  this.newValues = this.images;
                }
              } else {
                this.$message({
                  message: res.data.msg,
                  type: "warning",
                });
              }
            });
          },
          event.size
        );
      }
    },
    datadragEnd(evt) {
      this.newValues = this.images;
    },
    acv(a, b, c) {
      this.images.push({
        type: "image",
        src: a.data.fileUrl,
      });
      if (this.XMaxImg == 1) {
        this.newValues = JSON.parse(JSON.stringify(this.images))[0].src;
      } else {
        this.newValues = this.images;
      }
    },
    remove(index) {
      this.images.splice(index, 1);
      if (this.XMaxImg == 1) {
        this.newValues = "";
        this.$refs.uploada.clearFiles();
      } else {
        this.newValues = this.images;
        this.$refs.uploada.clearFiles();
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type;
      if (
        isJPG != "image/jpeg" &&
        isJPG != "image/png" &&
        isJPG != "image/jpg"
      ) {
        alert("上传图片类型错误,只能是 jpeg/png/jpg 格式的图片");
        return false;
      }

      if (file.size / 1024 > (this.maximum || 200)) {
        this.$message({
          type: "warning",
          message: "“" + file.name + "”图片超过" + (this.maximum || 200) + "kB",
        });
        return false;
      } else if (!/^image/.test(file.type)) {
        this.$message({
          type: "warning",
          message: "“" + file.name + "”不是图片",
        });
        return false;
      }
    },
    CoverImgs(data) {
      this.images = [];
      this.Img = [];
      if (this.XMaxImg === 1) {
        if (data) {
          let arr = { type: "image", src: data };
          this.images.push(arr);
        }
      } else {
        let obj = {};
        if (typeof data === "string") {
          obj = JSON.parse(data);
          this.Img = JSON.parse(JSON.stringify(obj));
          for (let i in obj) {
            this.images.push({
              type: "image",
              src: obj[i].src,
            });
          }
        } else if (typeof data === "object") {
          this.Img = JSON.parse(JSON.stringify(data));
          for (let i in data) {
            this.images.push({
              type: "image",
              src: data[i].src,
            });
          }
        }
      }
    },
  },
};
</script>

<style>
</style>